const db = require("../models");
const Sale_employee = db.sale_employee;
const Op = db.Sequelize.Op;

// Create and Save
exports.create = (req, res) => {
      // Validate request
  if (!req.body||req.body.length===0) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }

  // Create a Sale_employee
  const sale_employee = req.body;

  // Save Sale_employee in the database
  Sale_employee.create(sale_employee)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Sale_employee."
      });
    });
  
};

// Create and Save All
exports.createAll = (req, res) => {
  // Validate request
  if (!req.body||req.body.length===0) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }
  
  // Create Admin_groups
  const admin_groups = req.body;

  // Save Admin_groups in the database
  Sale_employee.bulkCreate(admin_groups)
  .then(data => {
    res.send(data);
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while creating the Sale_employee."
    });
  });

};

// Retrieve all from the database.
exports.findAll = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;
  const condition = hiden
  ?{
    'deletedAt':{
      [Op.not]:null
    }  
  }
  :{};

  Sale_employee.findAndCountAll({ offset: offset, limit: limit ,paranoid:mode,where:condition})
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving sale_employee."
      });
    });
  
};

// Retrieve a single one with attr and value
exports.findByAttr = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;

  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  if(!all){
    condition['deletedAt']=hiden
    ?{
        [Op.not]:null 
    }
    :null;
  };
  Sale_employee.findAndCountAll({ 
    where: condition , offset:offset,limit:limit,paranoid:mode
  }).then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving sale_employee."
      });
    });
  
};

// Find a single one with an id
exports.findOne = (req, res) => {
    const id = req.params.id;
    const mode = req.query.mode=='all'?false:true;

    Sale_employee.findByPk(id,{paranoid:mode})
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving Sale_employee with id=" + id
        });
      });
  
};

// Update one by the id in the request
exports.update = (req, res) => {
    
    const id = req.params.id;
    Sale_employee.update(req.body, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Sale_employee was updated successfully."
        });
      } else {
        res.send({
          message: `Cannot update Sale_employee with id=${id}. Maybe Sale_employee was not found or req.body is empty!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error updating Sale_employee with id=" + id
      });
    });
  
};

// Update one by attr in the request
exports.updateByAttr = (req, res) => {
    
  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  Sale_employee.update(req.body, {
  where: condition
}).then(num => {
    if(num==0){
      res.send({
        message: `Cannot update Sale_employee with ${attr}=${value}. Maybe Sale_employee was not found or req.body is empty!`
      });
    }else{
      res.send({
        message: `${num} items has been updated with ${attr}=${value}.`,
        count: parseInt(num)
      });
    }
  })
  .catch(err => {
    res.status(500).send({
      message: "Error updating Sale_employee." 
    });
  });

};

// update all by ids
exports.updateAll = async (req, res) => {
 
  var messages=[];
  var count = 0;
  for(let index in req.body){
    
    const id = parseInt(req.body[index].id);
    await Sale_employee.update(req.body[index], {
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          messages[index]=
          {
            id: id,
            tip: `Sale_employee with id=${id} was updated successfully.`
          };
          count++;
        } else {
          messages[index]=
          {
            id:id,
            warnning: `Cannot update Sale_employee with id=${id}. Maybe Sale_employee was not found or req.body is empty!`
          };
        }
      })
      .catch(err => {
        messages[index]={
          id:id,
          warnning: "Error updating Sale_employee with id=" + id
        };
      });

  };

  res.send({
    success_count:count,
    messages:messages
  });
};
// Delete one with the specified id in the request
exports.delete = (req, res) => {
    const id = req.params.id;
    const mode = req.query.mode=='true'?true:false;
    Sale_employee.destroy({
      where: { id: id },
      force: mode
    }).then(num => {
      if (num == 1) {
        res.send({
          message: `Sale_employee with id=${id} was deleted successfully!`,
          mode:mode
        });
      } else {
        res.send({
          message: `Cannot delete Sale_employee with id=${id}. Maybe Sale_employee was not found!`,
          mode:mode
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Sale_employee with id=" + id,
        mode:mode
      });
    });
};

// Delete all from the database.
exports.deleteAll = (req, res) => {
  const mode = req.query.mode=='true'?true:false;
    Sale_employee.destroy({
        where: {},
        truncate: false,
        force:mode
      })
        .then(nums => {
          res.send({ message: `${nums} items of table Sale_employee were deleted successfully!`,
          mode:mode
         });
        })
        .catch(err => {
          res.status(500).send({
            message:
              err.message || "Some error occurred while removing all sale_employee.",
            mode:mode
          });
        });
};

// Delete all from the database by Attr.
exports.deleteAllByAttr = (req, res) => {
    const mode = req.query.mode=='true'?true:false;
    const attr = req.params.attr;
    const value = req.params.value;
    const condition = {};
    condition[attr]=value;
    Sale_employee.destroy({
        where: condition,
        truncate: false,
        force:mode
      })
        .then(nums => {
          res.send({ 
            message: `${nums} items of table Sale_employee were deleted successfully!`,
            mode:mode
         });
        })
        .catch(err => {
          res.status(500).send({
            message: err.message || "Some error occurred while removing all sale_employee.",
            mode: mode
          });
        });
};

// Restore softdeleted items by id
exports.restore = (req,res)=>{
    const id = req.params.id;

    Sale_employee.restore({
      where:{id:id}
    })
      .then(() => {
        const data=Sale_employee.findByPk(id);
        return data
      })
      .then(data=>{
        res.send({
          result:"Restore Sale_employee with id=" + id +" successfully!",
          data:data
        });
      })
      .catch(err => {
        res.status(500).send({
          message: "Error recovery Sale_employee with id=" + id +".Maybe it doesn't exist or just an unknown error."
        });
      });

};

// Restore softdeleted items All by ids
exports.restoreAll =async (req,res)=>{
  const ids = req.body.ids;

  let count = 0;
  let result = {};
  for(let id of ids){
    await Sale_employee.restore({
      where:{id:id}
    })
      .then(() => {
        const data=Sale_employee.findByPk(id);
        return data
      })
      .then(data=>{
        count++;
        result[id]={
          result:"Restore Sale_employee with id=" + id +" successfully!",
          data:data
        };
      })
      .catch(err => {
        result[id]={
          message: "Error recovery Sale_employee with id=" + id +".Maybe it doesn't exist or just an unknown error."
        };
      });
  };
  res.send({
    success:count,
    error:ids.length-count,
    rows:result
  });
};

// Restore softdeleted items All by attr
exports.restoreAllByAttr = (req,res)=>{
    
  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  Sale_employee.restore({
    where:condition
  })
    .then(() => {
      console.log("testing");
      const data=Sale_employee.findAll({where:condition});
      return data
    })
    .then(data=>{
      res.send({
        result:"Restore Sale_employee successfully!",
        count:data.length,
        data:data
      });
    })
    .catch(err => {
      res.status(500).send({
        message: "Error recovery Sale_employee.Maybe it doesn't exist or just an unknown error."
      });
    });  

};
